//
//  ChangeLanguageViewController.m
//  LFCWarmSystem
//
//  Created by Kill on 16/4/28.
//  Copyright © 2016年 李福才. All rights reserved.
//

#import "ChangeLanguageViewController.h"
#import "DBOperation.h"

@interface ChangeLanguageViewController ()<UITableViewDataSource,UITableViewDelegate,MFMessageComposeViewControllerDelegate>{
    NSArray *languageArr;
    NSArray *languageShortArr;
    NSArray *msgContectArr;
    NSInteger selectedRow;
    

}

@end

@implementation ChangeLanguageViewController
@synthesize modelPhone;
//@synthesize lblWaiting;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:NSLocalizedString(@"WarmSystem_Sample",@"报警系统") leftBarItemsTitle:@[NSLocalizedString(@"Cancel_Sample", @"取消")] rightBarItemsTitle:@[NSLocalizedString(@"Complete_Sample", @"完成")]];
    [self uiInit];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)uiInit{
    languageArr = [NSArray arrayWithObjects: @"English",@"简体中文", @"Français", @"Deutsch",@"Pусский",@"Nederlands",@"Italiano",
                                             @"Español",@"Português do Brasil", @"Português",@"ภาษาไทย",@"Eλληνικά", @"Svenska", @"Norsk",
                                             @"Suomi",@"Dansk", @"Polski",@"Slovensky", @"Česky", @"Magyar", @"Bulgarian", nil];
    languageShortArr = [NSArray arrayWithObjects:  @"en",@"zh", @"fr", @"de",@"ru",@"nl",@"it",
                                                   @"es",@"pt-pt", @"pt",@"th",@"hu", @"sw", @"no",
                                                   @"fi",@"da", @"pl",@"sk", @"cs", @"gr", @"bg", nil];
    msgContectArr = [NSArray arrayWithObjects:@"0001",@"0086",@"0033",@"0049",@"0007", @"0031",@"0039",
                                              @"0034",@"0055",@"0351",@"0066",@"0030",@"0046",@"0047",
                                              @"0358",@"0045",@"0048",@"0421",@"0420",@"0036",@"0359",nil];
    
    selectedRow = [languageShortArr containsObject:self.modelPhone.language]?[languageShortArr indexOfObject:self.modelPhone.language]:-1;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    tableView.backgroundColor = TABLEVIEWCOLOR;
    tableView.rowHeight = TABLEVIEWCELLSMALLHEIGHT;
    tableView.delegate = self;
    tableView.dataSource = self;
    UILabel *lblHeadView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, tableView.frame.size.height/5.0)];
    lblHeadView.text = NSLocalizedString(@"ChangeLanguage_Sample",@"修改主机语言");
    lblHeadView.textColor = COLOR_MAINHEAD;
    lblHeadView.font = TABLEHEADFONT;
    lblHeadView.backgroundColor = BACKGROUNDVIEWCOLOR;
    lblHeadView.textAlignment = NSTextAlignmentCenter;
    [tableView setTableHeaderView:lblHeadView];
    [tableView setTableFooterView:[UIView new]];
    [self.view addSubview:tableView];
    
}
#pragma mark-UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
    [newCell setAccessoryType:UITableViewCellAccessoryCheckmark];
    if (selectedRow != indexPath.row){
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:0]];
        [oldCell setAccessoryType:UITableViewCellAccessoryNone];
        selectedRow = indexPath.row;
    }
}

#pragma mark-UITableViewDataSource
//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    return nil;
//}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  languageArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"languageCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%@%@" ,cellID,indexPath]];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%@%@" ,cellID,indexPath]];
        cell.textLabel.textColor = TEXTCOLOR;
        cell.textLabel.font = TABLECELLTEXTFONT;
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = COLOR_CELLSELECTED_LIGHTBLUE;
        
    }
    cell.textLabel.text = languageArr[indexPath.row];
    cell.textLabel.highlightedTextColor = WHITECOLOR;
    if (indexPath.row == selectedRow) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    return cell;
}

#pragma mark-Send Message
-(void)showSMSPicker:(NSString *)MSGContent{
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
    if (messageClass != nil) {
        // Check whether the current device is configured for sending SMS messages
        if ([messageClass canSendText]) {
            MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
            picker.recipients = [NSArray arrayWithObjects:self.modelPhone.phoneNumber, nil];
            picker.messageComposeDelegate = self;
            picker.body = [NSString stringWithFormat:@"%@",MSGContent];
            [self presentViewController:picker animated:YES completion:^{
            }];
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"DeviceCantMSG", @"设备没有短信功能")  message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"Close_Sample", @"  关闭") otherButtonTitles: nil];
            [alert show];
        }
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"VersionProblem", @"iOS版本过低,iOS4.0以上才支持程序内发送短信") message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"Close_Sample", @"  关闭") otherButtonTitles: nil];
        [alert show];
    }
}

#pragma mark-MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    
    
    switch (result)
    {
        case MessageComposeResultCancelled: {
            NSLog(@"Result: SMS sending canceled");
//            UIViewController *presentedVC = [self getCurrentVC];
//            [presentedVC.view addSubview:self.lblWaiting];
        }break;
        case MessageComposeResultSent:{
            NSLog(@"Result: SMS sent");
            //DB 操作记录用户选择的主机语言
            self.modelPhone.language = [languageShortArr objectAtIndex:selectedRow];
            DBOperation * dbo = [DBOperation getDBOperateInstance];
            [dbo updateMainAccountWithModel:self.modelPhone];
//            UIViewController *presentedVC = [self getCurrentVC];
//            [presentedVC.view addSubview:self.lblWaiting];
        }break;
        case MessageComposeResultFailed:{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"SendMSGFail", @"短信发送失败")  message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"Close_Sample", @"  关闭") otherButtonTitles: nil];
            [alert show];
        }
            break;
        default:
            NSLog(@"Result: SMS not sent");
            break;
    }
    
//    [NSThread sleepForTimeInterval:2.5];
//    [self.lblWaiting removeFromSuperview];
//    [NSThread sleepForTimeInterval:2.5];
    [self dismissViewControllerAnimated:YES completion:^{
        [self dismissViewControllerAnimated:YES completion:^{}];

    }];
}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}
-(void)rightAction:(id)sender{
    
    self.modelPhone.language = [languageShortArr objectAtIndex:selectedRow];
    DBOperation * dbo = [DBOperation getDBOperateInstance];
    [dbo updateMainAccountWithModel:self.modelPhone];
    [self showSMSPicker:[msgContectArr objectAtIndex:selectedRow]];
}
-(void)backAction:(id)sender{
    [self dismissViewControllerAnimated:YES completion:^{}];
}


@end
